<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-row>{{ Item_entryForm.id ? '试题编辑' : '试题录入' }}</el-row>
        <el-divider></el-divider>
        <el-form
          :model="Item_entryForm"
          :rules="Item_entryRules"
          ref="Item_entryForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="Item_entryForm.subjectID"
              placeholder="请选择"
              style="width: 400px"
              @change="changeSubject"
            >
              <el-option
                v-for="item in subject_List"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="Item_entryForm.catalogID"
              filterable
              allow-create
              default-first-option
              placeholder="请选择"
              style="width: 400px"
              :clearable="clearable"
            >
              <el-option
                v-for="item in catalogueList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="Item_entryForm.enterpriseID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in EnterpriseList"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="城市:" prop="cityGroup">
            <el-select
              v-model="Item_entryForm.province"
              placeholder="请选择"
              style="width: 198px"
              @change="changeCity"
              prop="province"
            >
              <el-option
                v-for="(province, index) in cityList"
                :key="index"
                :label="province"
                :value="province"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="Item_entryForm.city"
              placeholder="请选择"
              style="width: 198px; margin-left: 5px"
              prop="city"
            >
              <el-option
                v-for="(city, index) in placeList"
                :key="index"
                :label="city"
                :value="city"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="Item_entryForm.direction"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item, index) in directionList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="Item_entryForm.questionType">
              <el-radio
                v-for="item in questionTypeList"
                :label="StringTransition(item.value)"
                :key="item.value"
                @change="questionTypesCut(item.value)"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <el-form-item label="难度:" prop="difficulty">
            <el-radio
              v-model="Item_entryForm.difficulty"
              :label="StringTransition(item.value)"
              v-for="item in difficultyList"
              >{{ item.label }}</el-radio
            >
          </el-form-item>

          <el-form-item label="题干:" prop="question">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="Item_entryForm.question"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorChange($event)"
            >
            </quill-editor>
          </el-form-item>

          <el-form-item
            label="选项:"
            prop="options"
            label-width="100px"
            v-if="Item_entryForm.questionType !== '3'"
          >
            <!-- 题型对应的选项 -->
            <template>
              <el-row
                v-for="(item, index) in Item_entryForm.options"
                :key="index"
                style="margin: -2px 0"
              >
                <!-- 单选类型 -->
                <div v-if="Item_entryForm.questionType === '1'">
                  <!-- 单选按钮 -->
                  <el-radio-group ref="checkboxOrRadio" v-model="options_d">
                    <el-radio
                      :label="index"
                      @change="OptionChange"
                      :value="item.isRight"
                      >{{ item.code + '：' }}</el-radio
                    >
                  </el-radio-group>
                  <!-- 表单 -->
                  <el-input
                    style="width: 260px"
                    v-model="item.title"
                    clearable
                  ></el-input>
                  <!-- 封装图片上传组件 -->
                  <upload-img
                    ref="refUploadImg"
                    :item="item"
                    :index="index"
                    :options="Item_entryForm.options"
                  ></upload-img>
                </div>

                <!-- 多选框 -->
                <div v-if="Item_entryForm.questionType === '2'">
                  <el-checkbox v-model="item.isRight">
                    {{ item.code + '：' }}
                  </el-checkbox>

                  <!-- 表单 -->
                  <el-input
                    style="width: 260px"
                    v-model="item.title"
                    clearable
                  ></el-input>

                  <!-- 封装图片上传组件 -->
                  <upload-img
                    ref="refUploadImg"
                    :item="item"
                    :index="index"
                    :options="Item_entryForm.options"
                  ></upload-img>
                </div>
              </el-row>
            </template>

            <el-button
              type="danger"
              size="small"
              :disabled="Item_entryForm.questionType === '2' ? false : true"
              @click="addOptions"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item label="解析视频:" prop="videoURL">
            <el-input
              style="width: 400px"
              v-model="Item_entryForm.videoURL"
            ></el-input>
          </el-form-item>

          <el-form-item label="答案解析:" prop="answer">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="Item_entryForm.answer"
              ref="myQuillEditor2"
              :options="editorOption"
              @blur="onEditorChange($event)"
            >
            </quill-editor>
          </el-form-item>

          <el-form-item label="题目备注:" prop="remarks">
            <el-input
              type="textarea"
              :rows="5"
              v-model="Item_entryForm.remarks"
              style="width: 400px"
              resize="vertical"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="试题标签:" prop="tags">
            <el-select
              v-model="Item_entryForm.tags"
              placeholder="请选择试题标签"
              multiple
              clearable
            >
              <el-option
                v-for="item in tagsList"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-button
            :type="Item_entryForm.id ? 'success' : 'primary'"
            style="margin: 0 0 22px 100px"
            @click="submit"
            >{{ Item_entryForm.id ? '确认修改' : '确认提交' }}</el-button
          >
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import EnteringQuilEditor from '../components/entering-quillEditor.vue'
// 导入 状态,难度,题型,方向列表
import {
  status,
  difficulty,
  questionType,
  direction
} from '@/api/hmmm/constants.js'
// 基础题库添加接口
import { add } from '@/api/hmmm/questions.js'
// 获取学科简单列表接口
import { simple } from '@/api/hmmm/subjects.js'
//  获取企业列表接口
import { list } from '@/api/hmmm/companys.js'
//  获取学科目录的接口
import { list as subjectList } from '@/api/hmmm/directorys.js'
// 获取试题标签的接口
import { list as tagsList } from '@/api/hmmm/tags.js'
// 导入城市列表方法
import { provinces, citys } from '@/api/hmmm/citys.js'
// 图片上传组件
import uploadImg from './components/UploadImg.vue'
// 引入富文本编辑器
import { quillEditor } from 'vue-quill-editor'

// 基础题库详情,基础题库修改
import {
  detail as basicsSubjectDetail,
  update as basicsSubjectEdit
} from '@/api/hmmm/questions.js'

export default {
  data () {
    // 校验城市的自定义规则
    const validateProvince = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '))
      } else {
        rule.required = true
        callback()
      }
    }
    const validateGroup = (rule, value, callback) => {
      if (!value && !this.Item_entryForm.city) {
        return callback(new Error('请选择地区'))
      } else {
        callback()
      }
    }
    // 地区
    const validateCity = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '))
      } else {
        callback()
      }
    }
    return {
      // 富文本编辑器配置
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote', 'code-block'], // 引用  代码块
            // [{ direction: 'rtl' }], // 文本方向
            // [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            // [{ align: [] }], // 对齐方式
            ['image', 'link'] // 视频 链接
            // ['clean'] // 清除文本格式
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 试题录入表单
      Item_entryForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市：
        city: '', //地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: false, filelist: [] },
          { code: 'B', title: '', img: '', isRight: false, filelist: [] },
          { code: 'C', title: '', img: '', isRight: false, filelist: [] },
          { code: 'D', title: '', img: '', isRight: false, filelist: [] }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 试题录入表单校验
      Item_entryRules: {
        // 学科
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        // 目录
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ],
        // 企业
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        // 城市：
        cityGroup: [
          {
            required: true,
            validator: validateGroup,
            trigger: ['blur', 'change']
          }
        ],
        province: [
          { validator: validateProvince, trigger: ['blur', 'change'] }
        ],
        city: [{ validator: validateCity, trigger: ['blur', 'change'] }],

        // 方向
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        // 题型
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        // 难度
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        // 题干
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],

        // 答案解析
        answer: [
          { required: true, message: '请输入题干', trigger: 'blur' }
          //  { validator: validateAnswer, trigger: 'blur' }
        ]
      },
      isRightEnumerate: {
        0: false,
        1: true
      }, //isRight枚举
      subject_List: [], //学科列表
      EnterpriseList: [], //企业列表
      cityList: [], // 城市列表,
      placeList: [], //地区列表
      catalogueList: [], //目录列表
      tagsList: [], //试题标签列表
      directionList: [], // 方向列表
      questionTypeList: [], // 题型列表
      difficultyList: [], //难度列表
      clearable: false, // 目录表单是否可清空默认false
      options_d: '', //控制单选 (单选默认)
      options_List: [], //控制多选框
      EditId: '' //编辑id
    }
  },
  components: {
    EnteringQuilEditor,
    uploadImg,
    quillEditor
  },
  created () {
    this.getSubjectBriefnessList()
    this.getEnterpriseList()
    this.provinces()
    this.TagsList()

    // console.log(this.$route.query.id)
    // 接收基础题库传递的id
    if (this.$route.query.id) {
      // 选项回显触发的方法
      this.multipleData({ id: this.EditId })
    }
    // this.multipleData({ id: 42 })
  },
  methods: {
    // 获取学科简单列表
    async getSubjectBriefnessList () {
      const res = await simple()
      // console.log(res.data)
      this.subject_List = res.data
    },
    // 获取企业列表
    async getEnterpriseList () {
      const res = await list()
      // console.log(res)
      this.EnterpriseList = res.data.items
    },
    // 获取城市列表
    provinces () {
      const cityList = provinces()
      // console.log(cityList)
      this.cityList = cityList
    },
    // 城市列表发生变化会触发的方法
    changeCity () {
      this.citys()
      this.Item_entryForm.city = ''
    },
    // 获取地方列表
    citys () {
      const placeList = citys(this.Item_entryForm.province)
      // console.log(placeList)
      this.placeList = placeList
    },
    // 学科发生变化会触发的方法
    changeSubject () {
      // console.log(val)
      this.getSubjectDeatil()
      this.clearable = true
      // if (typeof Array) {
      this.Item_entryForm.catalogID = ''
      // }
    },
    // 获取学科目录的方法
    async getSubjectDeatil () {
      const res = await subjectList({
        ...this.Item_entryForm,
        page: 1,
        pagesize: 1000
      })
      this.catalogueList = res.data.items
    },
    // 获取试题标签的方法
    async TagsList () {
      const res = await tagsList({
        page: 1,
        pagesize: 100,
        state: 1
      })
      // console.log(res.data.items)
      this.tagsList = res.data.items
    },
    // 单选框数据更改触发的回调
    OptionChange (val) {
      // console.log(val)
      this.Item_entryForm.options.forEach(item => {
        item.isRight = false
      })
      this.Item_entryForm.options[val].isRight = true
    },
    // 题型切换触发的方法
    questionTypesCut (val) {
      // console.log(val)
      if (val !== '') {
        this.Item_entryForm.options = [
          { code: 'A', title: '', img: '', isRight: false, filelist: [] },
          { code: 'B', title: '', img: '', isRight: false, filelist: [] },
          { code: 'C', title: '', img: '', isRight: false, filelist: [] },
          { code: 'D', title: '', img: '', isRight: false, filelist: [] }
        ]
        this.options_d = ''
      }
    },
    // 增加选项与答案触发的回调
    addOptions () {
      this.Item_entryForm.options.push({
        code: this.getCode(this.Item_entryForm.options.length),
        title: '',
        img: '',
        isRight: false,
        filelist: []
      })
    },
    // 定义选项前code标题回调函数
    getCode (i) {
      // 入参i需要一个整数
      // 返回一个大写字母
      return String.fromCharCode(65 + i)
      // 返回一个小写字母
      // return String.fromCharCode(97+i)
    },
    // 选项回显触发的方法
    async multipleData (data) {
      console.log(data)
      const res = await basicsSubjectDetail(data)
      console.log(res.data)
      // console.log(res.data)
      // if (res.data.questionType !== '2') return
      // 处理后端返回的选项数据
      const optionsManage = res.data.options.map(item => {
        // this.isRightEnumerate[item.isRight] 枚举转化
        return {
          code: item.code,
          title: item.title,
          img: item.img,
          isRight: this.isRightEnumerate[item.isRight],
          filelist: item.filelist
        }
      })
      // const NewoptionsManage = optionsManage.reverse()
      // 处理后端返回的tags标签数据
      // console.log(res.data.tags.split(','))

      const singleAry = res.data.options.map(item => {
        // console.log(item.isRight)
        return item.isRight
      })
      // console.log(singleAry)
      // 得到符合条件数据的下标值 singleAry.indexOf(1)
      this.options_d = singleAry.indexOf(1)
      console.log(singleAry)
      this.Item_entryForm = {
        ...res.data,
        tags:
          res.data.tags === '' || res.data.tags === null
            ? ''
            : res.data.tags.split(','),
        options: optionsManage
      }
      // console.log(optionsManage)
    },
    onEditorChange (val) {
      console.log(val)
    },
    // 提交表单
    submit () {
      this.$refs.Item_entryForm.validate(async valid => {
        // console.log(valid)
        // if (!valid) return
        // // 校验 是否为单选的数组数据
        // const filterArr = this.Item_entryForm.options.filter(item => {
        //   return item.isRight === true
        // })
        // console.log(filterArr)
        // await add({
        //   ...this.Item_entryForm,
        //   options: filterArr
        // })

        if (!valid) return
        // 校验 是否为单选的数组数据
        console.log(this.Item_entryForm)
        const tagsString = this.Item_entryForm.tags.join(',')
        console.log(tagsString)
        // 判断是否为编辑
        if (this.Item_entryForm.id) {
          await basicsSubjectEdit({
            ...this.Item_entryForm,
            tags: tagsString
          })
        } else {
          await add({
            ...this.Item_entryForm,
            tags: tagsString
          })
        }

        this.$message.success(this.Item_entryForm.id ? '编辑成功' : '添加成功')
        this.$refs.Item_entryForm.resetFields()
        this.Item_entryForm.province = ''
        this.$router.push({
          path: 'list'
        })
      })
    },
    // 将数据转换为字符串的方法
    StringTransition (val) {
      return String(val)
    }
  },
  watch: {
    // 侦听 方向列表数据的变化
    directionList: {
      // handler 数据发生变化，需要执行的处理程序
      // deep: true  如果true,代表深度监听，不仅会监听地址的变化，还会监听对象内部属性的变化
      // immediate: 立即 立刻  是否立即监听 默认是false  如果是true,代表页面一加载，会先执行一次处理程序
      handler (value) {
        // console.log('你变了', value)
        // console.log(this.Item_entryForm.questionType)
        this.directionList = direction
      },
      deep: true,
      immediate: true
    },
    questionType: {
      handler (value) {
        // console.log('你变了', value)
        this.questionTypeList = questionType
      },
      deep: true,
      immediate: true
    },
    difficulty: {
      handler () {
        this.difficultyList = difficulty
      },
      deep: true,
      immediate: true
    },
    // 编辑id
    EditId: {
      handler () {
        this.EditId = +this.$route.query.id
      },
      deep: true,
      immediate: true
    },

    $route: {
      handler (val) {
        console.log(val)

        // 判断是否为空对象
        // es6 新增语法
        // console.log(Object.keys(val.query).length === 0)
        if (Object.keys(val.query).length === 0) {
          this.$refs.Item_entryForm.resetFields() //重置表单
          this.Item_entryForm = {
            subjectID: '', // 学科
            catalogID: '', // 目录
            enterpriseID: '', // 企业
            province: '', // 城市：
            city: '', //地区
            direction: '', // 方向
            questionType: '1', // 题型
            difficulty: '1', // 难度
            question: '', // 题干
            options: [
              { code: 'A', title: '', img: '', isRight: false, filelist: [] },
              { code: 'B', title: '', img: '', isRight: false, filelist: [] },
              { code: 'C', title: '', img: '', isRight: false, filelist: [] },
              { code: 'D', title: '', img: '', isRight: false, filelist: [] }
            ], // 选项
            videoURL: '', // 解析视频
            answer: '', // 答案解析
            remarks: '', // 题目备注
            tags: '' // 试题标签
          }
          this.options_d = ''
          this.options_List = []
        }
      },
      deep: true
      // immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 0;

  .el-row {
    padding: 18px 20px;
  }
  .el-divider {
    margin: 0;
    background-color: #ebeef5;
  }
  .el-form {
    padding: 20px;
    .ql-editor {
      min-height: 200px;
    }
    .ql-code-block {
      margin-left: 10px;
    }
    .ql-formats:nth-child(3) {
      margin-right: 0;
    }

    .el-checkbox-group {
      display: inline-block;
      margin-right: 5px;
    }
  }
}
</style>
